package com.shunbo.convenient.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shunbo.convenient.service.CustomerInfoService;
import com.shunbo.convenient.service.OrdersService;
import com.shunbo.convenient.service.ProductOrderService;
import com.shunbo.convenient.service.ProductService;
import com.shunbo.convenient.utils.ConvenientResult;
import com.shunbo.convenient.utils.DateUtils;
import com.shunbo.convenient.utils.RandomValueUtil;
import com.shunbo.convenient.vo.*;
import net.sf.json.JSONObject;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Project Name: sns-business
 * File Name: WeAppLoginBiz.java
 * Date: 2017年1月13日下午1:06:17
 * Author: zhao.zhibo@xiaoyi.com
 * Explain: 微信小程序登录
 */
@RestController
@RequestMapping("/customerInfo")
public class CustomerInfoController {
    /**
     * author 李俊标
     * 2018-4-19
     */

    private static final String APPID = "wx1564032be1a4de0a";
    private static final String SECRET = "05ac863ba8e146b8667b9e3a597839fc";

    @Resource
    private CustomerInfoService customerInfoService;
    @Resource
    private OrdersService ordersService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductOrderService productOrderService;

    //获取凭证校检接口
    @RequestMapping("/login")
    public ConvenientResult login(@RequestBody CustomerInfo customerInfo) {
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID +
                "&secret=" + SECRET + "&js_code=" + customerInfo.getCode() + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            //解析从微信服务器获得的openid和session_key;
            System.out.println(sessionData);
            JSONObject jSONObject = JSONObject.fromObject(sessionData);
            //获取用户的唯一标识
            String openid = jSONObject.getString("openid");
            //获取会话秘钥
            //String session_key = jSONObject.getString("session_key");
            System.out.println(openid);
            CustomerInfo info = new CustomerInfo();
            info.setUserId(openid);
            List<CustomerInfo> all = customerInfoService.findAll(info);
            if(all.size() > 0){
                return ConvenientResult.build(200, "成功", all.get(0));
            }else{
                customerInfo.setCreateTime(DateUtils.getDate());
                customerInfo.setUserId(openid);
                customerInfoService.save(customerInfo);
                return ConvenientResult.build(200, "成功", customerInfo);
            }
        }
        return ConvenientResult.build(500, "微信验证失败,请重试", false);
    }
    //获取凭证校检接口
    @RequestMapping("/code")
    public ConvenientResult code(String code) {
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID +
                "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            //解析从微信服务器获得的openid和session_key;
            System.out.println(sessionData);
            JSONObject jSONObject = JSONObject.fromObject(sessionData);
            //获取用户的唯一标识
            String openid = jSONObject.getString("openid");
            //获取会话秘钥
            return ConvenientResult.build(200, "获取openId", openid);
        }
        return ConvenientResult.build(500, "微信验证失败,请重试", false);
    }

    /**
     * 会员列表
     *
     * @param customerInfo 收货地址
     * @return Result结果集
     */
    @RequestMapping("/list")
    public ConvenientResult getCustomerList(@RequestBody CustomerInfo customerInfo) {
        try {

            Double money = 0.0;
            PageHelper.startPage(customerInfo.getPageNo(), 10);
            List<CustomerInfo> all = customerInfoService.findAll(customerInfo);
            for (CustomerInfo cus: all
                 ) {
                Orders orders = new Orders();
                orders.setUserId(cus.getUserId());
                List<Orders> ordersList = ordersService.findAll(orders);
                customerInfo.setOrders(ordersList.size());
                for (Orders order:ordersList
                ) {
                    ProductOrder productOrder = new ProductOrder();
                    productOrder.setOid(order.getOrderId());
                    System.out.println("查询订单");
                    List<ProductOrder> all1 = productOrderService.findAll(productOrder);
                    for (ProductOrder po: all1
                    ) {
                        Product byId = productService.findById(po.getPid() + "");
                        money+= po.getNum()*byId.getMoney();
                    }
                }
                cus.setMoney(money);
            }
            PageInfo<CustomerInfo> pageInfo = new PageInfo<>(all);
            Map<String, Object> map = new HashMap<>();
            map.put("productList", all);
            map.put("pageNo", customerInfo.getPageNo());
            map.put("count", pageInfo.getTotal());
            return ConvenientResult.build(200, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 更新用户
     * @param customerInfo 用户信息
     * @return Result结果集
     */
    @RequestMapping("/update")
    public ConvenientResult updateCustomerInfo(@RequestBody CustomerInfo customerInfo){
        try {
            Integer save = customerInfoService.update(customerInfo);
            return ConvenientResult.build(200,"成功",save);
        }catch (Exception e){
            e.printStackTrace();
            return ConvenientResult.build(500,"系统错误",e.getStackTrace());
        }
    }

    /**
     * 添加用户
     * @param customerInfo 用户信息
     * @return Result结果集
     */
    @RequestMapping("/save")
    public ConvenientResult saveCustomerInfo(@RequestBody CustomerInfo customerInfo){
        try {
            Integer save = customerInfoService.save(customerInfo);
            return ConvenientResult.build(200,"成功",save);
        }catch (Exception e){
            e.printStackTrace();
            return ConvenientResult.build(500,"系统错误",e.getStackTrace());
        }
    }

    /**
     * 删除用户
     * @param customerInfo 用户信息
     * @return Result结果集
     */
    @RequestMapping("/delete")
    public ConvenientResult deleteCustomerInfo(@RequestBody CustomerInfo customerInfo){
        try {
            Integer save = customerInfoService.delete(customerInfo.getId()+"");
            return ConvenientResult.build(200,"成功",save);
        }catch (Exception e){
            e.printStackTrace();
            return ConvenientResult.build(500,"系统错误",e.getStackTrace());
        }
    }

    /**
     * 会员列表
     *
     * @param customerInfo 收货地址
     * @return Result结果集
     */
    @RequestMapping("/findOne")
    public ConvenientResult getCustomerFindOne(@RequestBody CustomerInfo customerInfo) {
        try {

            Double money = 0.0;
            List<CustomerInfo> all = customerInfoService.findAll(customerInfo);
            for (CustomerInfo cus: all
            ) {
                Orders orders = new Orders();
                orders.setUserId(cus.getUserId());
                List<Orders> ordersList = ordersService.findAll(orders);
                customerInfo.setOrders(ordersList.size());
                for (Orders order:ordersList
                ) {
                    ProductOrder productOrder = new ProductOrder();
                    productOrder.setOid(order.getOrderId());
                    List<ProductOrder> all1 = productOrderService.findAll(productOrder);
                    for (ProductOrder po: all1
                    ) {
                        Product byId = productService.findById(po.getPid() + "");
                        money+= po.getNum()*byId.getMoney();
                        po.setProduct(byId);
                    }
                    order.setProductOrder(all1);
                }

                cus.setMoney(money);
            }
            return ConvenientResult.build(200, "成功", all);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }


    /**
     * 会员列表
     *
     * @param  ids ids
     * @return Result结果集
     */
    @RequestMapping("/coupon")
    public ConvenientResult getCustomerCoupon(String ids) {
        try {

            Map result = new HashMap();
            String[] split = ids.split(",");
            for (String str : split){
                if(str.equals("NA")){
                    result.put(RandomValueUtil.getChineseName(),RandomValueUtil.getTelephone());
                }else{
                    CustomerInfo customer = new CustomerInfo();
                    customer.setUserId(str);
                    CustomerInfo byId = customerInfoService.findAll(customer).get(0);
                    result.put(byId.getUserName(),byId.getPhone());
                }
            }
            return ConvenientResult.build(200, "成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

}
